package com.yami.shop.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.app.utils.HttpResult;
import com.yami.shop.bean.app.dto.ProductDto;
import com.yami.shop.bean.cashregisterapp.AppCashRegisterSystemUser;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.LoginHistMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.sys.model.SysConfig;
import com.yami.shop.sys.service.SysConfigService;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/app/homeData")
@Api(tags = "首页接口")
public class HomeDataController {

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;

    @Autowired
    private AppCashRegisterSystemUserService appCashRegisterSystemUserService;

    @Autowired
    private AuthorizationServerTokenServices yamiTokenServices;

    @Autowired
    private LoginHistMapper loginHistMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserDepositService userDepositService;

    @Autowired
    private SysConfigService  sysConfigService;

    @Autowired
    private OldUserService oldUserService;


    /**
     * 获取店铺信息
     * @param userId
     * @return
     */
    @PostMapping("/getShopInformation")
    public HttpResult getShopInformation(Long userId){
        //获取店铺名称以及收银员姓名
        AppCashRegisterSystemUser appCashRegisterSystemUser = appCashRegisterSystemUserService.getAppCashRegisterSystemUserByUserId(userId);
        //根据shopId获取店铺的名称
        if(appCashRegisterSystemUser!=null){
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(appCashRegisterSystemUser.getShopId());
            if(shopDetail!=null){
                appCashRegisterSystemUser.setShopName(shopDetail.getShopName());
            }
        }
        return HttpResult.success(appCashRegisterSystemUser);
    }

    /**
     * 获取所有的商品类型
     */
    @PostMapping("/getCategory")
    public HttpResult getCategory(){
        List<Category> categoryList = categoryService.getAllCategory(SecurityUtils.getSysUser().getShopId());
        return HttpResult.success(categoryList);
    }


    /**
     * 获取店铺所有类型的商品
     */
    @PostMapping("/getProductByShopId")
    @ResponseBody
    public HttpResult getProductByShopId(Long categoryId, PageParam<ProductDto> page){
        //当传值为-1的时候,查询所有类型商品数据。
        IPage<ProductDto> productList = productService.pageByCategoryId(page,categoryId,SecurityUtils.getSysUser().getShopId());
        return HttpResult.success(productList);
    }

    /**
     * 根据商品名称或是商品编号查询商品
     */
    @PostMapping("/getProductListBySearchField")
    public HttpResult getProductListBySearchField(String searchField){
        List<Product> productList = productService.getProductListBySearchField(SecurityUtils.getSysUser().getShopId(),searchField);
        return HttpResult.success(productList);
    }

    /**
     * 根据手机号查询对应的会员
     */
    @PostMapping("/getMember")
    public HttpResult getMember(String tel,PageParam<User> page){
      //  IPage<User> user = userService.getMember(page,tel);
        List<User> userList = userService.getUserByPhone(tel);
        Long shopId = SecurityUtils.getSysUser().getShopId();
        if(CollectionUtils.isNotEmpty(userList)){
            for(User user:userList){
                //查询用户当前店铺余额
                String userId = user.getUserId();
                OldUser oldUser = oldUserService.getOldUserByShopId(userId,shopId);
                if(oldUser!=null){
                    BigDecimal oldAccount = oldUser.getAccount();
                    user.setOldAccount(oldAccount.doubleValue());
                }
            }
        }

        return HttpResult.success(userList);
    }

    /**
     * 退出登陆
     */
    @PostMapping(value = "/sys/logout")
    public HttpResult logout() {
        //更新用户登出时间
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        OAuth2AuthenticationDetails detail = (OAuth2AuthenticationDetails)authentication.getDetails();
        //根据token值修改登陆时间
        loginHistMapper.updateLoginHist(new Date(),detail.getTokenValue());
        SecurityContextHolder.clearContext();
        return HttpResult.success();
    }

    /**
     * 通过产品的barcode码查询对应的商品信息
     */
    @PostMapping("/getProductByBarCode")
    @ResponseBody
    public HttpResult getProductByBarCode(String barCode){
        Product productParam = new Product();
        productParam.setBarCode(barCode);
        productParam.setShopId(SecurityUtils.getSysUser().getShopId());
        productParam.setSaleType(2);
        Product product = productService.getProductByBarCode(productParam);
        return HttpResult.success(product);
    }

    /**
     * 取单
     */
    @PostMapping("/getNotPayOrder")
    @ResponseBody
    public HttpResult getNotPayOrder(){
        //查询该营业员处理的待支付订单
        List<Order> orderList = orderService.getNotPayOrder(SecurityUtils.getSysUser().getUserId());
        return HttpResult.success(orderList);
    }


    /**
     * 新增会员
     */
    @PostMapping("/addNewMember")
    @ResponseBody
    public HttpResult addNewMember(@RequestBody User user){
        //查询有没有重复的电话号码
        String mobile = user.getUserMobile();
        User oldUser = userService.selectUserByPhoneOne(mobile);
        if(oldUser!=null){
            return HttpResult.failure("电话号码已经存在!");
        }
        //新增用户
        String userId  = IdUtil.simpleUUID();
        user.setUserId(userId);
        user.setModifyTime(new Date());
        user.setUserRegtime(new Date());
        userService.save(user);
        if(user.getUserAccount()==null){
            user.setUserAccount(0.00);
        }
        return  HttpResult.success(user);
    }


    /**
     * 会员充值
     */
    @PostMapping("/depositMoney")
    @ResponseBody
    public HttpResult depositMoney(String mobile,double money){
        //根据手机号码获取会员
        User user = userService.selectUserByPhoneOne(mobile);
        UserDeposit userDeposit = new UserDeposit();
        if(user!=null) {
            userDeposit.setUserId(user.getUserId());
            userDeposit.setCashier(SecurityUtils.getSysUser().getUserId());
            userDeposit.setShopId(SecurityUtils.getSysUser().getShopId());
            userDeposit.setAmount(money);
            userDeposit.setCreateTime(new Date());
        }
        userDepositService.depositMoney(userDeposit);
        return HttpResult.success();
    }

    /**
     * 根据手机号或手机号后4位,或者用户昵称查询会员
     */
    @PostMapping("/getUserByMobileOrNickName")
    @ResponseBody
    public  HttpResult getUserByMobileOrNickName(String searchFiled){
        List<User> userList = userService.getUserByMobileOrNickName(searchFiled);
        return  HttpResult.success(userList);
    }

    /**
     * 设置app版本号
     */
    @PostMapping("/SetAppVersion")
    @ResponseBody
    public HttpResult SetAppVersion(@RequestBody SysConfig sysConfig){
        String newAppVersiom = sysConfigService.getValue(sysConfig.getParamValue());
        String oldAppVersion = sysConfigService.getValue("app_version");
        if(!newAppVersiom.equals("")||newAppVersiom!=null){
            BigDecimal newVersion = new BigDecimal(newAppVersiom);
            BigDecimal oldVersion = new BigDecimal(oldAppVersion);
            if(newVersion.compareTo(oldVersion)>-1){
                sysConfigService.updateValueByKey("app_version",sysConfig.getParamValue());
                return  HttpResult.success("0");
            }else{
                return  HttpResult.success("-1");
            }
        }

        return HttpResult.success();
    }

    /**
     * 设置版本号
     */
    @GetMapping("/getAppVersion")
    @ResponseBody
    public HttpResult getAppVersion(){
        String latestVersion = sysConfigService.getValue("app_version");
        String latestCode = sysConfigService.getValue("code");
        String  minimumVersion = sysConfigService.getValue("minimumVersion");
        String  minimumCode = sysConfigService.getValue("sysConfigService");
        String address = sysConfigService.getValue("address");
        VersionDto versionDto = new VersionDto();
        versionDto.setAddress(address);
        versionDto.setLatestCode(latestCode);
        versionDto.setLatestVersion(latestVersion);
        versionDto.setMinimumCode(minimumCode);
        versionDto.setMinimumVersion(minimumVersion);
        return HttpResult.success(versionDto);
    }

    /**
     * 根据userId获取用户
     */
    @PostMapping("/getUserByUserId")
    @ResponseBody
    public HttpResult getUserByUserId(@RequestBody AppCashRegisterSystemUser appCashRegisterSystemUser){
        Long userId = appCashRegisterSystemUser.getUserId();
        AppCashRegisterSystemUser appCashRegisterSystemUser1 = appCashRegisterSystemUserService.getAppCashRegisterSystemUserByUserId(userId);
        return HttpResult.success(appCashRegisterSystemUser1);
    }
}
